package com.fzu.geometa.metadata.eventdriven.listener;

import com.fzu.geometa.metadata.eventdriven.event.MetadataAddEvent;
import com.fzu.geometa.metadata.model.po.Register;
import com.fzu.geometa.metadata.service.MetadataService;
import com.fzu.geometa.metadata.service.RegisterService;
import com.fzu.geometa.metadata.util.HostHolder;
import com.fzu.geometa.mq.EventProducer;
import com.fzu.geometa.mq.constant.EntityType;
import com.fzu.geometa.mq.constant.Topic;
import com.fzu.geometa.mq.model.Event;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
public class MetadataAddListener implements ApplicationListener<MetadataAddEvent> {
    @Autowired
    EventProducer eventProducer;
    @Autowired
    RegisterService registerService;
    @Autowired
    MetadataService metadataService;
    @Autowired
    HostHolder hostHolder;

    @Override
    public void onApplicationEvent(MetadataAddEvent event) {
        Long cid = event.getCid();
        Long userId = hostHolder.getUser().getId();
        Register register = registerService.getById(cid);
        // 触发元数据发布事件
        if (register != null) {
            String content = metadataService.getMetadata(cid);
            Event publishEvent = new Event()
                    .setTopic(Topic.PUBLISH)
                    .setUserId(userId)
                    .setEntityId(cid)
                    .setEntityType(EntityType.Metadata)
                    .setData("coverageId", register.getCoverageId())
                    .setData("description", register.getDescription())
                    .setData("createTime", register.getCreateTime())
                    .setData("content", content)
                    .setData("subtype", register.getSubtype());
            eventProducer.fireEvent(publishEvent);
        }
    }
}
